﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using DBFiller.Controler;
using System.Threading;
using DBFiller.Entities;

namespace DBFiller.UI
{
	public partial class MainWindow : Form
	{
		private string fileName = "";
		private static bool running;
		private string count;	

		public MainWindow()
		{
			InitializeComponent();
			for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
				cbConnectionStringName.Items.Add(new ComboBoxItem()
				{
					Name = ConfigurationManager.ConnectionStrings[i].Name,
					Value = ConfigurationManager.ConnectionStrings[i].ConnectionString
				});

			if (ConfigurationManager.ConnectionStrings.Count > 0)
				cbConnectionStringName.SelectedIndex = 0;
		}

		private void otwórzPlikToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (ofdFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				lFile.Text = fileName = ofdFile.FileName;
				this.bStart.Enabled = true;
			}
		}

		private void bStart_Click(object sender, EventArgs e)
		{
			string connectionString = cbConnectionStringName.SelectedIndex > -1 ?
					((ComboBoxItem)cbConnectionStringName.SelectedItem).Value.ToString()
					: Config.Config.GetConnectionString("Default");
			bool clear = this.chkbxClear.Checked;

			Thread thread = new Thread(()=>LoadFile(connectionString,clear));
			count = "";
			tsslProgress.Visible = true;
			running = true;
			tspbStatus.Visible = true;
			tsslStatus.Visible = true;
			bStart.Visible = false;
			thread.Start();
		}

		private void LoadFile(string connectionString, bool clearFirst)
		{
			if (!string.IsNullOrEmpty(fileName))
			{
				try
				{
					Filler filler = new Filler(connectionString.ToString());
					string[] data;

					if((bool)clearFirst )
						filler.ClearDatabase();
					filler.InsertQuestions();
					filler.InsertRegions();
					filler.InsertStates();

					using (FileStream file = new FileStream(fileName, FileMode.Open))
					using (StreamReader streamReader = new StreamReader(file))
						data = streamReader.ReadToEnd().Split(new char[] { '\n' });

					for (int i = 0; i < data.Length; i++)
					{
						count = string.Format("{0} / {1}", i, data.Length);
						filler.AddRow(data[i]);
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
					MessageBox.Show(ex.StackTrace);
				}

			}
			running = false;
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			if (running == false)
			{
				tspbStatus.Visible = false;
				tsslStatus.Visible = false;
				tsslProgress.Visible = false;
				bStart.Visible = true;
			}
			else
				tsslProgress.Text = count;
		}
	}
}
